"use client"

import type React from "react"
import { useRef, useEffect } from "react"
import { View, Text, StyleSheet, TouchableOpacity, Animated, Platform } from "react-native"
import { LinearGradient } from "expo-linear-gradient"
import { Volume2, Mic, Play, Square, Star } from "lucide-react-native"
import { theme } from "../../constants/theme"

interface Phoneme {
    letter: string
    sound: string
}

interface ReadingCardProps {
    word: string
    phonetic: string
    meaning: string
    isPlaying?: boolean
    isRecording?: boolean
    recordingDuration?: number
    hasRecording?: boolean
    score?: number | null
    phonemes?: Phoneme[]
    onPlayAudio?: () => void
    onStartRecording?: () => void
    onStopRecording?: () => void
    onPlayRecording?: () => void
    onPhonemePress?: (phoneme: string, sound: string) => void
}

export const ReadingCard: React.FC<ReadingCardProps> = ({
    word,
    phonetic,
    meaning,
    isPlaying = false,
    isRecording = false,
    recordingDuration = 0,
    hasRecording = false,
    score = null,
    phonemes = [],
    onPlayAudio,
    onStartRecording,
    onStopRecording,
    onPlayRecording,
    onPhonemePress,
}) => {
    // 动画值
    const recordingPulse = useRef(new Animated.Value(1)).current
    const scoreScale = useRef(new Animated.Value(score ? 1 : 0)).current

    // 录音动画
    useEffect(() => {
        let animation: Animated.CompositeAnimation
        if (isRecording) {
            animation = Animated.loop(
                Animated.sequence([
                    Animated.timing(recordingPulse, {
                        toValue: 1.2,
                        duration: 1000,
                        useNativeDriver: true,
                    }),
                    Animated.timing(recordingPulse, {
                        toValue: 1,
                        duration: 1000,
                        useNativeDriver: true,
                    }),
                ]),
            )
            animation.start()
        } else {
            recordingPulse.setValue(1)
        }

        return () => {
            if (animation) {
                animation.stop()
            }
        }
    }, [isRecording, recordingPulse])

    // 评分动画
    useEffect(() => {
        if (score !== null) {
            Animated.spring(scoreScale, {
                toValue: 1,
                friction: 8,
                tension: 40,
                useNativeDriver: true,
            }).start()
        } else {
            scoreScale.setValue(0)
        }
    }, [score, scoreScale])

    // 渲染星级评分
    const renderStars = () => {
        return Array(5)
            .fill(0)
            .map((_, index) => (
                <View key={index} style={{ marginHorizontal: 2 }}>
                    <Animated.View>
                        <Star
                            size={24}
                            color={score && index < score ? theme.colors.secondary.orange.default : theme.colors.neutral.lightGray}
                            fill={score && index < score ? theme.colors.secondary.orange.default : "none"}
                        />
                    </Animated.View>
                </View>
            ))
    }

    return (
        <View style={styles.card}>
            {/* 单词 */}
            <Text style={styles.word}>{word}</Text>

            {/* 音标和发音按钮 */}
            <View style={styles.phoneticContainer}>
                <Text style={styles.phonetic}>{phonetic}</Text>
                <TouchableOpacity style={styles.soundButton} onPress={onPlayAudio} disabled={isPlaying} activeOpacity={0.7}>
                    <Volume2 size={20} color={theme.colors.primary.default} />
                </TouchableOpacity>
            </View>

            {/* 中文释义 */}
            <Text style={styles.meaning}>{meaning}</Text>

            {/* 录音播放按钮 - 仅在有录音时显示 */}
            {hasRecording && (
                <TouchableOpacity
                    style={styles.recordingPlayButton}
                    onPress={onPlayRecording}
                    disabled={isPlaying}
                    activeOpacity={0.7}
                >
                    <LinearGradient
                        colors={["rgba(91, 142, 244, 0.1)", "rgba(91, 142, 244, 0.2)"]}
                        style={styles.recordingPlayButtonGradient}
                    >
                        <Play size={20} color={theme.colors.primary.default} />
                        <Text style={styles.recordingPlayText}>{isPlaying ? "播放中..." : "播放我的录音"}</Text>
                    </LinearGradient>
                </TouchableOpacity>
            )}

            {/* 音素分解 */}
            {phonemes.length > 0 && score !== null && (
                <Animated.View
                    style={[
                        styles.phonemesContainer,
                        {
                            transform: [{ scale: scoreScale }],
                        },
                    ]}
                >
                    {phonemes.map((phoneme, index) => (
                        <TouchableOpacity
                            key={index}
                            style={styles.phonemeItem}
                            onPress={() => onPhonemePress && onPhonemePress(phoneme.letter, phoneme.sound)}
                            activeOpacity={0.7}
                        >
                            <Text style={styles.phonemeLetter}>{phoneme.letter}</Text>
                            <Text style={styles.phonemeSound}>{phoneme.sound}</Text>
                            <Text style={styles.phonemeScore}>0</Text>
                        </TouchableOpacity>
                    ))}
                </Animated.View>
            )}

            {/* 评分 */}
            {score !== null && (
                <Animated.View
                    style={[
                        styles.scoreContainer,
                        {
                            transform: [{ scale: scoreScale }],
                        },
                    ]}
                >
                    <Text style={styles.scoreLabel}>评分: {score}</Text>
                    <View style={styles.starsContainer}>{renderStars()}</View>
                </Animated.View>
            )}

            {/* 录音控制 */}
            <View style={styles.controls}>
                <TouchableOpacity
                    style={styles.recordButton}
                    onLongPress={onStartRecording}
                    onPressOut={isRecording ? onStopRecording : undefined}
                    delayLongPress={500}
                    activeOpacity={0.7}
                >
                    <LinearGradient colors={theme.colors.primary.gradient} style={styles.recordButtonGradient}>
                        <Animated.View
                            style={[
                                styles.recordButtonInner,
                                {
                                    transform: [{ scale: recordingPulse }],
                                },
                            ]}
                        >
                            {isRecording ? (
                                <Square size={32} color={theme.colors.neutral.white} />
                            ) : (
                                <Mic size={32} color={theme.colors.neutral.white} />
                            )}
                        </Animated.View>
                    </LinearGradient>
                </TouchableOpacity>
            </View>

            {/* 录音提示 */}
            <Text style={styles.recordingHint}>
                {isRecording ? `录音中 ${recordingDuration}s` : hasRecording ? "长按重新录音" : "长按开始录音"}
            </Text>
        </View>
    )
}

const styles = StyleSheet.create({
    card: {
        flex: 1,
        backgroundColor: theme.colors.neutral.white,
        borderRadius: theme.borderRadius.extraLarge,
        padding: theme.spacing.xl,
        alignItems: "center",
        ...Platform.select({
            ios: {
                shadowColor: "rgba(0, 0, 0, 0.1)",
                shadowOffset: { width: 0, height: 4 },
                shadowOpacity: 0.3,
                shadowRadius: 8,
            },
            android: {
                elevation: 4,
            },
        }),
    },
    word: {
        fontSize: 36,
        fontWeight: theme.fontWeight.bold,
        color: theme.colors.primary.default,
        marginBottom: theme.spacing.md,
        textAlign: "center",
    },
    phoneticContainer: {
        flexDirection: "row",
        alignItems: "center",
        marginBottom: theme.spacing.lg,
    },
    phonetic: {
        fontSize: theme.fontSize.md,
        color: theme.colors.neutral.gray,
        marginRight: theme.spacing.sm,
    },
    soundButton: {
        width: 36,
        height: 36,
        borderRadius: 18,
        backgroundColor: "rgba(91, 142, 244, 0.1)",
        alignItems: "center",
        justifyContent: "center",
    },
    meaning: {
        fontSize: theme.fontSize.md,
        color: theme.colors.neutral.darkGray,
        textAlign: "center",
        marginBottom: theme.spacing.xl,
    },
    phonemesContainer: {
        flexDirection: "row",
        justifyContent: "center",
        flexWrap: "wrap",
        gap: theme.spacing.sm,
        marginBottom: theme.spacing.lg,
    },
    phonemeItem: {
        alignItems: "center",
        backgroundColor: theme.colors.neutral.lightGray,
        borderRadius: theme.borderRadius.medium,
        padding: theme.spacing.sm,
        minWidth: 45,
        height: 70,
    },
    phonemeLetter: {
        fontSize: theme.fontSize.md,
        fontWeight: theme.fontWeight.bold,
        color: theme.colors.primary.default,
        marginBottom: 2,
    },
    phonemeSound: {
        fontSize: theme.fontSize.xs,
        color: theme.colors.neutral.darkGray,
        marginBottom: 2,
    },
    phonemeScore: {
        fontSize: theme.fontSize.sm,
        fontWeight: theme.fontWeight.semiBold,
        color: theme.colors.secondary.orange.default,
    },
    scoreContainer: {
        alignItems: "center",
        marginVertical: theme.spacing.lg,
    },
    scoreLabel: {
        fontSize: theme.fontSize.lg,
        fontWeight: theme.fontWeight.semiBold,
        color: theme.colors.neutral.black,
        marginBottom: theme.spacing.sm,
    },
    starsContainer: {
        flexDirection: "row",
        gap: theme.spacing.xs,
    },
    controls: {
        alignItems: "center",
        justifyContent: "center",
        marginTop: theme.spacing.xl,
    },
    recordButton: {
        width: 64,
        height: 64,
        borderRadius: 32,
        overflow: "hidden",
        ...Platform.select({
            ios: {
                shadowColor: theme.colors.primary.default,
                shadowOffset: { width: 0, height: 4 },
                shadowOpacity: 0.3,
                shadowRadius: 8,
            },
            android: {
                elevation: 6,
            },
        }),
    },
    recordButtonGradient: {
        width: "100%",
        height: "100%",
        alignItems: "center",
        justifyContent: "center",
    },
    recordButtonInner: {
        width: "100%",
        height: "100%",
        alignItems: "center",
        justifyContent: "center",
    },
    recordingHint: {
        textAlign: "center",
        fontSize: theme.fontSize.sm,
        color: theme.colors.neutral.gray,
        marginTop: theme.spacing.md,
    },
    recordingPlayButton: {
        marginBottom: theme.spacing.lg,
        borderRadius: theme.borderRadius.large,
        overflow: "hidden",
        alignSelf: "center",
    },
    recordingPlayButtonGradient: {
        flexDirection: "row",
        alignItems: "center",
        paddingVertical: theme.spacing.sm,
        paddingHorizontal: theme.spacing.lg,
        borderRadius: theme.borderRadius.large,
    },
    recordingPlayText: {
        fontSize: theme.fontSize.sm,
        color: theme.colors.primary.default,
        fontWeight: theme.fontWeight.medium,
        marginLeft: theme.spacing.xs,
    },
})

